package com.vecspace.web.filter;
 
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.vecspace.utils.log.HLogger;


/**
 * 记录每个请求执行耗费的时间
 * @author: wanghua
 */
public class ServletRequestMonitorFilter implements Filter{
	private static HLogger log = HLogger.getLog("dayu.metrics");
	private static long s_requestSeqNum = 0;
	private static Object objLock = new Object();
	@Override
	public void destroy() {
		
	}
	 

	/**
	 * 记录每个请求执行耗费的时间
	 */
	@Override
	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res; 
		long startTime=System.currentTimeMillis();
		chain.doFilter(request, response);
		long millseconds = System.currentTimeMillis()-startTime;
		if(millseconds > 3000 && log.isWarnEnabled()){
			long requestSeqNum=0;
			synchronized (objLock) {
				requestSeqNum = ++s_requestSeqNum;
			}
			log.warn("[XXXXX] {}-[{}]请求耗费[{}]ms",new Object[]{requestSeqNum,request.getRequestURI(),millseconds});
		}else if(millseconds > 2000 && log.isWarnEnabled()){
			long requestSeqNum=0;
			synchronized (objLock) {
				requestSeqNum = ++s_requestSeqNum;
			}
			log.warn("[XXXX] {}-[{}]请求耗费[{}]ms",new Object[]{requestSeqNum,request.getRequestURI(),millseconds});
		}else if(millseconds > 1000 && log.isInfoEnabled()){
			long requestSeqNum=0;
			synchronized (objLock) {
				requestSeqNum = ++s_requestSeqNum;
			}
			log.info("[XXX] {}-[{}]请求耗费[{}]ms",new Object[]{requestSeqNum,request.getRequestURI(),millseconds});
		}else if(millseconds > 500 && log.isInfoEnabled()){
			long requestSeqNum=0;
			synchronized (objLock) {
				requestSeqNum = ++s_requestSeqNum;
			}
			log.info("[XX] {}-[{}]请求耗费[{}]ms",new Object[]{requestSeqNum,request.getRequestURI(),millseconds});
		}else if(log.isTraceEnabled()){
			long requestSeqNum=0;
			synchronized (objLock) {
				requestSeqNum = ++s_requestSeqNum;
			}
			log.trace("[X] {}-[{}]请求耗费[{}]ms",new Object[]{requestSeqNum,request.getRequestURI(),millseconds});
		}
	}
	@Override
	public void init(FilterConfig config) throws ServletException {
		
	}
	
}
